import React, { memo, useRef, useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { Modal } from 'antd';
import MyForm from '@/components/MyForm';

const FormModal = ({ title, columns, width, obj, submitForm, cancel }) => {
  // 声明子组件ref
  const childRef = useRef();
  // loading
  const [confirmLoading, setConfirmLoading] = useState(false);

  const onOk = () => {
    setConfirmLoading(true);
    // 调用子组件中func
    childRef.current
      .validForm()
      .then((values) => {
        submitForm(values);
      })
      .catch((err) => {
        // console.log(err);
      })
      .finally(function () {
        setConfirmLoading(false);
      });
  };

  const onCancle = useCallback(() => {
    cancel();
  }, []);

  return (
    <Modal
      title={title}
      visible={!!obj}
      width={width}
      confirmLoading={confirmLoading}
      onOk={onOk}
      onCancel={onCancle}
      maskClosable={false}
    >
      <MyForm columns={columns} obj={obj} cRef={childRef} />
    </Modal>
  );
};

FormModal.propTypes = {
  title: PropTypes.string,
  columns: PropTypes.array.isRequired,
  obj: PropTypes.object,
  width: PropTypes.number,
  submitForm: PropTypes.func, // 提交表单的回调
  cancel: PropTypes.func,
};

export default memo(FormModal);
